package com.Xht.www.servlet;

//后端响应用户订房请求

import com.Xht.www.dao.RoomTypeInfoDAO;
import com.Xht.www.dao.UserHistoryOrdersDAO;
import com.Xht.www.dao.UserWalletBalanceDAO;
import com.Xht.www.dao.WalletTransactionLogDAO;
import com.Xht.www.po.RoomTypeInfoPO;
import com.Xht.www.po.UserHistoryOrdersPO;
import com.Xht.www.po.UserWalletBalancePO;
import com.Xht.www.po.WalletTransactionLogPO;
import com.Xht.www.dao.MerchantBlacklistDAO;
import com.Xht.www.po.MerchantBlacklistPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.stream.Collectors;
import java.util.List;

@WebServlet("/book-room")
public class BookRoomServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String requestBody = reader.lines().collect(Collectors.joining());
        String[] params = requestBody.split("&");
        int userId = Integer.parseInt(params[0].split("=")[1]);
        int roomTypeId = Integer.parseInt(params[1].split("=")[1]);
        String bookingDate = params[2].split("=")[1];
        String checkInDate = params[3].split("=")[1];
        String checkOutDate = params[4].split("=")[1];
        String roomTypeName = params[5].split("=")[1];
        String bedType = params[6].split("=")[1];
        String merchantName = params[7].split("=")[1];
        String contactPhone = params[8].split("=")[1];
        BigDecimal totalConsumption = new BigDecimal(params[9].split("=")[1]);

        boolean success = false;
        String message = "";

        try {
            // 检查用户是否在商家黑名单中
            MerchantBlacklistDAO blacklistDao = new MerchantBlacklistDAO();
            List<MerchantBlacklistPO> blacklistList = blacklistDao.getAllMerchantBlacklist();
            for (MerchantBlacklistPO blacklistPO : blacklistList) {
                if (blacklistPO.getUserId() == userId && blacklistPO.getMerchantName().equals(merchantName)) {
                    message = "您在该商家的黑名单中，无法订房";
                    break;
                }
            }

            if (message.isEmpty()) {
                UserWalletBalanceDAO walletDao = new UserWalletBalanceDAO();
                UserWalletBalancePO walletBalance = walletDao.getUserByUserId(userId);

                RoomTypeInfoDAO roomDao = new RoomTypeInfoDAO();
                RoomTypeInfoPO roomType = roomDao.queryRoomTypeInfoByRoomTypeId(roomTypeId);

                // 检查房间剩余数量
                if (roomType == null || roomType.getRemainingQuantity() <= 0) {
                    message = "该房间已无剩余房源";
                } else if (walletBalance != null && walletBalance.getTotalAmount().compareTo(roomType.getPrice()) >= 0) {
                    // 扣除余额
                    BigDecimal newBalance = walletBalance.getTotalAmount().subtract(roomType.getPrice());
                    walletBalance.setTotalAmount(newBalance);
                    walletDao.updateUserWalletBalance(walletBalance);

                    // 增加消费金额
                    BigDecimal newConsumptionAmount = walletBalance.getConsumptionAmount().add(roomType.getPrice());
                    walletBalance.setConsumptionAmount(newConsumptionAmount);
                    walletDao.updateUserWalletBalance(walletBalance);

                    // 减少房间剩余数量
                    int newRemainingQuantity = roomType.getRemainingQuantity() - 1;
                    roomType.setRemainingQuantity(newRemainingQuantity);
                    roomDao.updateRoomTypeInfo(roomType);

                    // 增加房型销量
                    int newSalesVolume = roomType.getSalesVolume() + 1;
                    roomType.setSalesVolume(newSalesVolume);
                    roomDao.updateRoomTypeInfo(roomType);

                    // 创建账单流水记录
                    WalletTransactionLogDAO logDao = new WalletTransactionLogDAO();
                    WalletTransactionLogPO log = new WalletTransactionLogPO();
                    log.setUserId(userId);
                    log.setWalletId(userId); // 假设walletid和userid相同
                    log.setTransactionType("消费");
                    log.setTransactionAmount(roomType.getPrice());
                    // 修改为当前时间
                    log.setTransactionTime(new Timestamp(System.currentTimeMillis()));

                    // 插入账单流水记录
                    if (logDao.insert(log)) {
                        // 创建历史订单记录
                        UserHistoryOrdersDAO orderDao = new UserHistoryOrdersDAO();
                        UserHistoryOrdersPO order = new UserHistoryOrdersPO();
                        order.setUserId(userId);
                        order.setMerchantName(merchantName);
                        order.setContactPhone(contactPhone);
                        order.setTotalConsumption(totalConsumption);
                        order.setRoomTypeName(roomTypeName);
                        order.setBedType(bedType);
                        order.setRoomTypeQuantity(1);
                        order.setOrderPlacementTime(new Timestamp(System.currentTimeMillis()));
                        order.setCheckInTime(Timestamp.valueOf(checkInDate + " 00:00:00"));
                        order.setCheckOutTime(Timestamp.valueOf(checkOutDate + " 00:00:00"));
                        order.setOrderStatus("正常");
                        order.setRemarks("无");

                        // 插入历史订单记录
                        if (orderDao.insertOrder(order)) {
                            success = true;
                            message = "订房成功，历史订单记录插入成功";
                        } else {
                            message = "订房成功，但历史订单记录插入失败";
                        }
                    } else {
                        message = "订房成功，但账单流水记录插入失败";
                    }
                } else {
                    message = "余额不足或房间信息错误";
                }
            }
        } catch (SQLException e) {
            message = "订房失败: " + e.getMessage();
        }

        String json = "{\"success\": " + success + ", \"message\": \"" + message + "\"}";
        out.print(json);
        out.flush();
        out.close();
    }
}
